<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\ApplicationFormModel;
use App\V3\V3_2_7\Models\ApplicationGoodsModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ApplicationFormService
{
    /**
     *添加申请表
     * Author: zlf
     * Created at 2024/6/3 14:08
     * @param $data
     * @return void
     */
    public static function addApplicationForm($data)
    {
        $title = $data['order_type'] == 1 ? '采购申请表' : '领用申请表';
        DB::beginTransaction();
        try {
            $saveData = $data;
            $saveData['created_at'] = $data['time'];
            unset($saveData["time"]);
            unset($saveData["goods_list"]);
            $applicationId = ApplicationFormModel::query()->insertGetId($saveData);
            if (!empty($data["goods_list"])) {
                $goodsList = $data["goods_list"];
                foreach ($goodsList as &$gVal) {
                    $goodsData = [
                        'main_id' => $data['main_id'],
                        'materiel_name' => $gVal['goods_name'],
                        'type_name' => $gVal['type_name'],
                        'materiel_class_id' => $gVal['sec_class_id'],
                    ];
                    if (!empty($gVal['type_name'])) {
                        $goodsData['type_name'] = $gVal['type_name'];
                    }
                    if (!empty($gVal['type_id'])) {//选择商品，查询是否更改
                        $goodsData['id'] = $gVal['type_id'];
                        $info = MaterielTypeModel::query()
                            ->where($goodsData)->first();
                        if (empty($info)) {//更改了，新建物料
                            unset($goodsData['id']);
                            if (!empty($gVal['goods_unit'])) {
                                $goodsData['materiel_unit'] = $gVal['goods_unit'];
                            }
                            $goodsData['cost'] = $gVal['price'];
                            $goodsData['remark'] = $gVal['remark'];
                            $goodsData['created_at'] = time();
                            $gVal['type_id'] = MaterielTypeModel::query()->insertGetId($goodsData);
                        }
                    } else {//新建申请单商品，查询物料是否存在，不存在创建物料商品
                        $info = MaterielTypeModel::query()
                            ->where($goodsData)->first();
                        if (!empty($info)) {//存在，弹框
                            throw new \Exception('物料商品`' . $gVal['goods_name'] . '`,已存在！');
                        } else {//不存在创建物料商品
                            if (!empty($gVal['goods_unit'])) {
                                $goodsData['materiel_unit'] = $gVal['goods_unit'];
                            }
                            $goodsData['cost'] = $gVal['price'];
                            $goodsData['remark'] = $gVal['remark'];
                            $goodsData['created_at'] = time();
                            $gVal['type_id'] = MaterielTypeModel::query()->insertGetId($goodsData);
                        }
                    }
                    $gVal['application_id'] = $applicationId;
                    $gVal['main_id'] = $data['main_id'];
                    $gVal['user_id'] = $data['user_id'];
                    $gVal['created_at'] = $data['time'];
                    $gVal['surplus_num'] = $gVal['num'];
                }
                ApplicationGoodsModel::query()->insert($goodsList);
            } else {
                throw new \Exception('请选择商品！');
            }
            CommonService::operateResult($data['user_id'], $data["time"], '', $title . ',创建成功');
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug($title . '异常:' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    /**
     *申请表列表
     * Author: zlf
     * Created at 2024/6/3 16:53
     * @param $condition
     * @param $data
     * @return void
     */
    public static function getApplicationList($data)
    {
        $masterOrderList = ApplicationFormModel::query()
            ->select(
                'a.*',
                'username',
                'nickname'
            )->from('application_form as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->where([
                'a.delete_flag' => 0,
                'a.repeal_status' => 0,
                'main_id' => $data['main_id']
            ])->where(function ($query) use ($data) {
                if (!empty($data['order_type'])) {
                    $query->where('order_type', $data['order_type']);
                }
                if (!empty($data['keyword'])) {
                    if (strlen($data['keyword']) == 13) {
                        $query->where('order_no', 'like', '%' . $data['keyword'] . '%');
                    } else {
                        $query->where('order_no', 'like', '%' . $data['keyword'] . '%');
                        $query->orWhere('username', 'like', '%' . $data['keyword'] . '%');
                        $query->orWhere('nickname', 'like', '%' . $data['keyword'] . '%');
                    }
                }
            })->orderBy('created_at', 'desc')->get();
        $orderList = [];
        if (!empty($masterOrderList->toArray())) {
            $masterOrderList = $masterOrderList->toArray();
            foreach ($masterOrderList as $key => $mVal) {
                $mVal['is_out'] = empty(ApplicationGoodsModel::query()
                    ->where([
                        'application_id' => $mVal['id'],
                        'delete_flag' => 0,
                        'main_id' => $data['main_id']
                    ])->sum('surplus_num')) ? 1 : 0;
                $mVal['operator_approver_username'] = '';
                $mVal['operator_approver_nickname'] = '';
                if (!empty($mVal['operator_approver_id'])) {
                    $mVal['operator_approver_username'] = AdminModel::query()
                        ->where('id', $mVal['operator_approver_id'])->first()['username'];
                    $mVal['operator_approver_nickname'] = AdminModel::query()
                        ->where('id', $mVal['operator_approver_id'])->first()['nickname'];
                }
                if (!empty($mVal['application_time']))
                    $mVal['application_time'] = date('Y年m月d日 H:i:s', $mVal['application_time']);
                if (!empty($mVal['approval_time']))
                    $mVal['approval_time'] = date('Y年m月d日 H:i:s', $mVal['approval_time']);
                if ($data['main_id'] == $data['user_id']) {
                    if ($data['user_id'] == $mVal['user_id']) {
                        $mVal['user_role'] = 1;
                    } else {
                        $mVal['user_role'] = 2;
                    }
                    $orderList[$key] = $mVal;
                } else {
                    if ($data['user_id'] == $mVal['user_id']) {
                        $mVal['user_role'] = 1;
                        $orderList[$key] = $mVal;
                    }
                }
                if (!empty($mVal['carbon_copy_recipients'])) {
                    if (strpos($mVal['carbon_copy_recipients'], ',') !== false) {
                        $recipientsArr = explode(',', $mVal['carbon_copy_recipients']);
                        if (in_array($data['user_id'], $recipientsArr)) {
                            $mVal['user_role'] = 3;
                            $orderList[$key] = $mVal;
                        }
                    } elseif ($data['user_id'] == $mVal['carbon_copy_recipients']) {
                        $mVal['user_role'] = 3;
                        $orderList[$key] = $mVal;
                    }
                }
                if (!empty($mVal['is_see_user'])) {
                    if (strpos($mVal['is_see_user'], ',') !== false) {
                        $userList = explode(',', $mVal['is_see_user']);
                    } else {
                        $userList[] = $mVal['is_see_user'];
                    }
                    foreach ($userList as $uVal) {
                        if ($data['user_id'] == $uVal) {
                            unset($orderList[$key]);
                        }
                    }
                }
            }
        }
        $currentPage = $data['currentPage'];
        $result = array_slice(array_values($orderList), --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
        return [
            'total' => count($orderList),
            'current_page' => $currentPage,
            'next_page_url' => count($result) < $data['pageSize'] ? null : config('app.url') . "get_application_form_list?=" . ($data['currentPage'] + 1),
            'prev_page_url' => $currentPage == 1 ? null : config('app.url') . "get_application_form_list?=" . ($currentPage - 1),
            "path" => config('app.url') . "get_application_form_list",
            "to" => $currentPage * $data['pageSize'],
            'data' => array_values($result),
            "per_page" => $data['pageSize']
        ];
    }

    /**
     *审批列表
     * Author: zlf
     * Created at 2024/6/3 16:53
     * @param $condition
     * @param $data
     * @return void
     */
    public static function checkApplicationList($data)
    {
        $masterOrderList = ApplicationFormModel::query()
            ->select(
                'a.*',
                'username',
                'nickname'
            )->from('application_form as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->where([
                'a.delete_flag' => 0,
                'a.repeal_status' => 0,
                'main_id' => $data['main_id']
            ])->where(function ($query) use ($data) {
                if (!empty($data['order_type'])) {
                    $query->where('order_type', $data['order_type']);
                }
                if (isset($data['approval_status'])) {
                    if (in_array($data['approval_status'], [0, 1, 2, 3])) {
                        $query->where('approval_status', $data['approval_status']);
                    }
                }
                if (!empty($data['keyword'])) {
                    if (strlen($data['keyword']) == 13) {
                        $query->where('order_no', 'like', '%' . $data['keyword'] . '%');
                    } else {
                        $query->where('order_no', 'like', '%' . $data['keyword'] . '%');
                        $query->orWhere('username', 'like', '%' . $data['keyword'] . '%');
                        $query->orWhere('nickname', 'like', '%' . $data['keyword'] . '%');
                    }
                }
            })->orderBy('created_at', 'desc')->get();
        $orderList = [];
        if (!empty($masterOrderList->toArray())) {
            $masterOrderList = $masterOrderList->toArray();
            foreach ($masterOrderList as $key => $mVal) {
                $mVal['is_out'] = empty(ApplicationGoodsModel::query()
                    ->where([
                        'application_id' => $mVal['id'],
                        'delete_flag' => 0,
                        'main_id' => $data['main_id']
                    ])->sum('surplus_num')) ? 1 : 0;
                $mVal['operator_approver_username'] = '';
                $mVal['operator_approver_nickname'] = '';
                if (!empty($mVal['operator_approver_id'])) {
                    $mVal['operator_approver_username'] = AdminModel::query()
                        ->where('id', $mVal['operator_approver_id'])->first()['username'];
                    $mVal['operator_approver_nickname'] = AdminModel::query()
                        ->where('id', $mVal['operator_approver_id'])->first()['nickname'];
                }
                if (!empty($mVal['application_time']))
                    $mVal['application_time'] = date('Y年m月d日 H:i:s', $mVal['application_time']);
                if (!empty($mVal['approval_time']))
                    $mVal['approval_time'] = date('Y年m月d日 H:i:s', $mVal['approval_time']);
                if ($data['main_id'] == $data['user_id']) {//主账号情况，判断是不是审批人，
                    if (!empty($mVal['approver'])) {
                        if (strpos($mVal['approver'], ',') !== false) {
                            $approverArr = explode(',', $mVal['approver']);
                            if (in_array($data['user_id'], $approverArr)) {
                                $mVal['user_role'] = 2;
                            } else {
                                $mVal['user_role'] = 1;
                            }
                        } elseif ($data['user_id'] == $mVal['approver']) {
                            $mVal['user_role'] = 2;
                        } else {
                            $mVal['user_role'] = 1;
                        }
                    } else {
                        $mVal['user_role'] = 1;
                    }
                    $orderList[$key] = $mVal;
                } else {
                    if ($data['user_id'] == $mVal['user_id']) {//自已创建的单子，判断是不是审批人，
                        if (!empty($mVal['approver'])) {
                            if (strpos($mVal['approver'], ',') !== false) {
                                $approverArr = explode(',', $mVal['approver']);
                                if (in_array($data['user_id'], $approverArr)) {
                                    $mVal['user_role'] = 2;
                                } else {
                                    $mVal['user_role'] = 1;
                                }
                            } elseif ($data['user_id'] == $mVal['approver']) {
                                $mVal['user_role'] = 2;
                            } else {
                                $mVal['user_role'] = 1;
                            }
                        } else {
                            $mVal['user_role'] = 1;
                        }
                        $orderList[$key] = $mVal;
                    } else {
                        if (!empty($mVal['approver'])) {//不是自已的单子，但我是审批人
                            if (strpos($mVal['approver'], ',') !== false) {
                                $approverArr = explode(',', $mVal['approver']);
                                if (in_array($data['user_id'], $approverArr)) {
                                    $mVal['user_role'] = 2;
                                    $orderList[$key] = $mVal;
                                }
                            } elseif ($data['user_id'] == $mVal['approver']) {
                                $mVal['user_role'] = 2;
                                $orderList[$key] = $mVal;
                            }
                        }
                    }
                }
            }
        }
        $currentPage = $data['currentPage'];
        $result = array_slice(array_values($orderList), --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
        return [
            'total' => count($orderList),
            'current_page' => $currentPage,
            'next_page_url' => count($result) < $data['pageSize'] ? null : config('app.url') . "get_application_form_list?=" . ($data['currentPage'] + 1),
            'prev_page_url' => $currentPage == 1 ? null : config('app.url') . "get_application_form_list?=" . ($currentPage - 1),
            "path" => config('app.url') . "get_application_form_list",
            "to" => $currentPage * $data['pageSize'],
            'data' => array_values($result),
            "per_page" => $data['pageSize']
        ];
    }

    /**
     *申请表详情
     * Author: zlf
     * Created at 2024/6/4 10:36
     * @param $data
     * @return void
     */
    public static function applicationFormInfo($data)
    {
        $info = ApplicationFormModel::query()
            ->select(
                'a.*',
                'username',
                'nickname'
            )->from('application_form as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->where([
                'a.id' => $data['id'],
                'a.delete_flag' => 0
            ])->first();
        if (!empty($info)) {
            $approverInfo = [];
            $recipientsInfo = [];
            $info['goods_list'] = '';
            $info['operator_approver_username'] = '';
            $info['operator_approver_nickname'] = '';
            if (!empty($info['operator_approver_id'])) {
                $info['operator_approver_username'] = AdminModel::query()
                    ->where('id', $info['operator_approver_id'])->first()['username'];
                $info['operator_approver_nickname'] = AdminModel::query()
                    ->where('id', $info['operator_approver_id'])->first()['nickname'];
            }
            $goodsList = ApplicationGoodsModel::query()
                ->where([
                    'application_id' => $info['id'],
                    'delete_flag' => 0
                ])->get();
            $info['is_out'] = 0;
            if (!empty($goodsList->toArray())) {
                $surplusNum = 0;
                foreach ($goodsList->toArray() as $gVal) {
                    $surplusNum += $gVal['surplus_num'];
                }
                $info['is_out'] = !empty($surplusNum) ? 0 : 1;
                $info['goods_list'] = $goodsList;
            }
            if (!empty($info['approver'])) {//审批人
                $approverInfo[] = $info['approver'];
                if (strpos($info['approver'], ',') !== false) {
                    $approverInfo = explode(',', $info['approver']);
                }
                $info['approver'] = AdminModel::query()
                    ->select(
                        'id as user_id',
                        'username',
                        'nickname'
                    )->whereIn('id', $approverInfo)->get();
            }

            if (!empty($info['carbon_copy_recipients'])) {//抄送人
                $recipientsInfo[] = $info['carbon_copy_recipients'];
                if (strpos($info['carbon_copy_recipients'], ',') !== false) {
                    $recipientsInfo = explode(',', $info['carbon_copy_recipients']);
                }
                $info['carbon_copy_recipients'] = AdminModel::query()
                    ->select(
                        'id as user_id',
                        'username',
                        'nickname'
                    )->whereIn('id', $recipientsInfo)->get();
            }
            if (!empty($data['user_id'])) {
                $info['check_user_role'] = "";
                $info['order_user_role'] = "";
                if ($info['user_id'] == $data['user_id']
                    && !in_array($data['user_id'], $approverInfo)
                    && !in_array($data['user_id'], $recipientsInfo)) {//是我创建的，不是审批人、抄送人
                    $info['order_user_role'] = 1;//申请单：1、自已创建的单子所有权限，查看、删除，撤销，确认收货
                    $info['check_user_role'] = 1;//审批：1、查看，
                } elseif ($info['user_id'] != $data['user_id']
                    && in_array($data['user_id'], $approverInfo)
                    && !in_array($data['user_id'], $recipientsInfo)) {//不是我创建的、不是抄送人，是审批人
                    $info['check_user_role'] = 2;//审批人：2拥有审批所有权限
                } elseif ($info['user_id'] != $data['user_id']
                    && in_array($data['user_id'], $approverInfo)
                    && in_array($data['user_id'], $recipientsInfo)) {//不是我创建的、是抄送人，是审批人
                    $info['order_user_role'] = 3;//申请单：3、抄送人角色（不是自己创建的单子，只有删除）
                    $info['check_user_role'] = 2;//审批：2、拥有审批所有权限
                } elseif ($info['user_id'] != $data['user_id']
                    && !in_array($data['user_id'], $approverInfo)
                    && in_array($data['user_id'], $recipientsInfo)) {//不是我创建的、不是审批人，是抄送人
                    $info['order_user_role'] = 3;//申请单：3、抄送人角色（不是自己创建的单子，只有删除）
                } elseif ($info['user_id'] == $data['user_id']
                    && in_array($data['user_id'], $approverInfo)
                    && !in_array($data['user_id'], $recipientsInfo)) {//是我创建的、不是抄送人,是审批人
                    $info['check_user_role'] = 2;//审批：2、拥有审批所有权限
                    $info['order_user_role'] = 1;//申请单：1、自已创建的单子所有权限，查看、删除，撤销，确认收货
                } elseif ($data['main_id'] == $data['user_id']
                    && !in_array($data['user_id'], $approverInfo)
                    && !in_array($data['user_id'], $recipientsInfo)) {//不是我创建的、不是抄送人,不是审批人,是主账号
                    $info['check_user_role'] = 3;//审批：3、查看删除
                    $info['order_user_role'] = 4;//申请单：4、查看，删除
                }
            }
            if (!empty($info['proof_img'])) {
                $proofImg = [];
                $proofImg[] = $info['proof_img'];
                if (strpos($info['proof_img'], ',') !== false) {
                    $proofImg = explode(',', $info['proof_img']);
                }
                $info['proof_img'] = $proofImg;
            }
            if (!empty($info['audit_proof_img'])) {
                $auditProofImg = [];
                $auditProofImg[] = $info['audit_proof_img'];
                if (strpos($info['audit_proof_img'], ',') !== false) {
                    $auditProofImg = explode(',', $info['audit_proof_img']);
                }
                $info['audit_proof_img'] = $auditProofImg;
            }
            if (!empty($info['delivery_proof_img'])) {
                $deliveryProofImg = [];
                $deliveryProofImg[] = $info['delivery_proof_img'];
                if (strpos($info['delivery_proof_img'], ',') !== false) {
                    $deliveryProofImg = explode(',', $info['delivery_proof_img']);
                }
                $info['delivery_proof_img'] = $deliveryProofImg;
            }
            if (!empty($info['application_time']))
                $info['application_time'] = date('Y年m月d日 H:i:s', $info['application_time']);
            if (!empty($info['approval_time']))
                $info['approval_time'] = date('Y年m月d日 H:i:s', $info['approval_time']);
        } else {
            return ['code' => 1, 'msg' => '没有找到，申请单信息！', 'data' => ''];
        }
        return ['code' => 0, 'msg' => 'success', 'data' => $info];
    }

    /**
     *删除申请表
     * Author: zlf
     * Created at 2024/6/4 14:43
     * @param $data
     * @return void
     */
    public static function delApplicationForm($data)
    {
        DB::beginTransaction();
        try {
            $recipientsInfo = [];
            $info = ApplicationFormModel::query()
                ->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->first();
            if (!empty($info)) {
                if (!empty($info['delete_flag'])) {
                    throw new \Exception('申请单，已删除！');
                }
                if (!empty($info['carbon_copy_recipients'])) {//抄送人
                    $recipientsInfo[] = $info['carbon_copy_recipients'];
                    if (strpos($info['carbon_copy_recipients'], ',') !== false) {
                        $recipientsInfo = explode(',', $info['carbon_copy_recipients']);
                    }
                }
                if ($data['user_id'] == $info['user_id']
                    && !in_array($data['user_id'], $recipientsInfo)) {
                    $info->is_see_user = !empty($info['is_see_user']) ? $info['is_see_user'] . ',' . $info['user_id'] : $info['user_id'];
                } elseif ($data['user_id'] == $info['user_id']
                    && in_array($data['user_id'], $recipientsInfo)) {
                    $info->is_see_user = !empty($info['is_see_user']) ? $info['is_see_user'] . ',' . $info['user_id'] : $info['user_id'];
                    if (!empty($recipientsInfo)) {
                        $recArr = [];
                        foreach ($recipientsInfo as $rVal) {
                            if ($data['user_id'] != $rVal) {
                                $recArr[] = $rVal;
                            }
                        }
                    }
                    $info->carbon_copy_recipients = implode(',', $recArr);
                } elseif ($data['user_id'] == $data['main_id']
                    && $data['user_id'] != $info['user_id']
                    && !in_array($data['user_id'], $recipientsInfo)) {
                    $info->is_see_user = !empty($info['is_see_user']) ? $info['is_see_user'] . ',' . $data['user_id'] : $data['user_id'];
                } elseif ($data['user_id'] != $info['user_id']
                    && in_array($data['user_id'], $recipientsInfo)) {
                    $info->is_see_user = !empty($info['is_see_user']) ? $info['is_see_user'] . ',' . $data['user_id'] : $data['user_id'];
                    if (!empty($recipientsInfo)) {
                        $recArr = [];
                        foreach ($recipientsInfo as $rVal) {
                            if ($data['user_id'] != $rVal) {
                                $recArr[] = $rVal;
                            }
                        }
                        $info->carbon_copy_recipients = implode(',', $recArr);
                    }
                } else {

                    throw new \Exception('您无权删除申请单！');
                }
            } else {
                throw new \Exception('没有找到，申请单信息！');
            }
            $info->save();
            CommonService::operateResult(
                $data['user_id'],
                $data['time'],
                '',
                '申请单号：' . $info['order_no'] . ',删除成功'
            );
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('删除申请表异常' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    /**
     *删除申请表
     * Author: zlf
     * Created at 2024/6/4 14:43
     * @param $data
     * @return void
     */
    public static function checkApplicationForm($data)
    {
        DB::beginTransaction();
        try {
            $approverInfo = [];
            $info = ApplicationFormModel::query()
                ->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->first();
            if (!empty($info)) {
                if (!empty($info['delete_flag'])) {
                    throw new \Exception('申请单，已删除！');
                }
                if (!empty($info['repeal_status'])) {
                    throw new \Exception('申请单，已撤销！');
                }
                if (!empty($info['approver'])) {//抄送人
                    $approverInfo[] = $info['approver'];
                    if (strpos($info['approver'], ',') !== false) {
                        $approverInfo = explode(',', $info['approver']);
                    }
                    if (in_array($data['user_id'], $approverInfo)) {
                        if (!empty($data['cause']))
                            $info->cause = $data['cause'];
                        $info->approval_time = time();
                        $info->operator_approver_id = $data['user_id'];
                        $info->approval_status = $data['approval_status'];

                    }
                }
                if (empty($info['approver']) || !in_array($data['user_id'], $approverInfo)) {
                    throw new \Exception('您无权审批申请单！');
                }
            } else {
                throw new \Exception('没有找到，申请单信息！');
            }
            $info->save();
            $checkName = '待审批';
            switch ($data['approval_status']) {
                case 1:
                    $checkName = '已同意';
                    break;
                case 2:
                    $checkName = '已拒绝';
                    break;
                case 3:
                    $checkName = '已完成';
                    break;
            }
            CommonService::operateResult(
                $data['user_id'],
                $data['time'],
                '',
                '申请单号：' . $info['order_no'] . ',' . $checkName
            );
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('审批申请表异常' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    /**
     *撤销申请表
     * Author: zlf
     * Created at 2024/6/4 14:43
     * @param $data
     * @return void
     */
    public static function repealApplicationForm($data)
    {
        DB::beginTransaction();
        try {
            $approverInfo = [];
            $info = ApplicationFormModel::query()
                ->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->first();
            if (!empty($info)) {
                if ($data['user_id'] != $info['user_id']) {
                    throw new \Exception('不是您的申请单，无权撤销！');
                }
                if (!empty($info['delete_flag'])) {
                    throw new \Exception('申请单，已删除！');
                }
                if (!empty($info['repeal_status'])) {
                    throw new \Exception('申请单，已撤销！');
                }
                $info->delete_flag = $data['repeal_status'];
                $info->repeal_status = $data['repeal_status'];
            } else {
                throw new \Exception('没有找到，申请单信息！');
            }
            $info->save();
            CommonService::operateResult(
                $data['user_id'],
                $data['time'],
                '',
                '申请单号：' . $info['order_no'] . ',撤销成功'
            );
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('删除申请表异常' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    /**
     *确认收货
     * Author: zlf
     * Created at 2024/6/4 14:43
     * @param $data
     * @return void
     */
    public static function ApplicationFormConfirmReceipt($data)
    {
        DB::beginTransaction();
        try {
            $approverInfo = [];
            $info = ApplicationFormModel::query()
                ->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->first();
            if (!empty($info)) {
                if (!empty($info['delete_flag'])) {
                    throw new \Exception('申请单，已删除！');
                }
                if (!empty($info['repeal_status'])) {
                    throw new \Exception('申请单，已撤销！');
                }
                if ($info['approval_status'] == 2) {
                    throw new \Exception('审批人已拒绝，不能确认收货！');
                }
                if (!in_array($info['approval_status'], [1, 3])) {
                    throw new \Exception('审批人未同意，不能上传！');
                }
                if ($data['user_id'] == $info['user_id']) {
                    if (!empty($data['audit_proof_img']))
                        $info->audit_proof_img = $data['audit_proof_img'];
                    $info->approval_status = $data['approval_status'];
                } else {
                    throw new \Exception('您无权限，点击确认收货！');
                }
            } else {
                throw new \Exception('没有找到，申请单信息！');
            }
            $info->save();
            CommonService::operateResult(
                $data['user_id'],
                $data['time'],
                '',
                '申请单号：' . $info['order_no'] . ',确认收货成功'
            );
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('确认收货异常' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    /**
     *上传交付凭证图片
     * Author: zlf
     * Created at 2024/6/4 14:43
     * @param $data
     * @return void
     */
    public static function uploadDeliveryProofImg($data)
    {
        DB::beginTransaction();
        try {
            $approverInfo = [];
            $info = ApplicationFormModel::query()
                ->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->first();
            if (!empty($info)) {
                if (!empty($info['delete_flag'])) {
                    throw new \Exception('申请单，已删除！');
                }
                if (!empty($info['repeal_status'])) {
                    throw new \Exception('申请单，已撤销！');
                }
                if ($info['approval_status'] == 2) {
                    throw new \Exception('审批人已拒绝，不能上传！');
                }
                if (!in_array($info['approval_status'], [1, 3])) {
                    throw new \Exception('审批人未同意，不能上传！');
                }
                if (!empty($info['approver'])) {
                    if (strpos($info['approver'], ',') !== false) {
                        $approverArr = explode(',', $info['approver']);

                        if (in_array($data['user_id'], $approverArr)) {
                            if (!empty($data['delivery_proof_img']))
                                $info->delivery_proof_img = $data['delivery_proof_img'];
                        } else {
                            throw new \Exception('您无权上传,交付凭证图片!');
                        }
                    } elseif ($data['user_id'] == $info['approver']) {
                        if (!empty($data['delivery_proof_img']))
                            $info->delivery_proof_img = $data['delivery_proof_img'];
                    } else {
                        throw new \Exception('您无权上传,交付凭证图片!');
                    }
                }
            } else {
                throw new \Exception('没有找到，申请单信息！');
            }
            $info->save();
            CommonService::operateResult(
                $data['user_id'],
                $data['time'],
                '',
                '申请单号：' . $info['order_no'] . ',上传成功'
            );
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('上传交付凭证图片异常' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }
}
